package org.gazzax.labs.solrwithmarc.index.processors;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.SolrInputField;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.update.AddUpdateCommand;
import org.apache.solr.update.processor.UpdateRequestProcessor;
import org.apache.solr.update.processor.UpdateRequestProcessorFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Converts Date and Time of Latest Transaction from MARC to SOLR format.
 * 
 * @author agazzarini
 * @since 1.0
 */
public class _005DateAndTimeOfLatestTransactionConverterFactory extends UpdateRequestProcessorFactory 
{
	private final static Logger LOGGER = LoggerFactory.getLogger(DateAndTimeOfLatestTransactionConverter.class);

	class DateAndTimeOfLatestTransactionConverter extends UpdateRequestProcessor
	{
		DateAndTimeOfLatestTransactionConverter(final UpdateRequestProcessor next) 
		{
			super(next);
		}
		
		@Override
		public void processAdd(final AddUpdateCommand command) throws IOException 
		{
			final SimpleDateFormat inputFormatter = new SimpleDateFormat("yyyyMMddHHmmss.S");
			inputFormatter.setLenient(false);
			
			SolrInputDocument document = command.getSolrInputDocument();
			SolrInputField marcDateField = document.removeField("005");
			if (marcDateField != null )
			{
				try 
				{
					Date dateAndTimeOfLatestTransaction = inputFormatter.parse((String) marcDateField.getFirstValue());
					if (dateAndTimeOfLatestTransaction != null)
					{
						document.setField("005", dateAndTimeOfLatestTransaction);
					}
				} catch (ParseException exception) 
				{
					LOGGER.error("Unable to format " + marcDateField + " as valid SOLR date");
				}
			}
			super.processAdd(command);
		}
	};
	
	@Override
	public UpdateRequestProcessor getInstance(
			final SolrQueryRequest req, 
			final SolrQueryResponse rsp, 
			final UpdateRequestProcessor next) 
	{
		return new DateAndTimeOfLatestTransactionConverter(next);
	}
}
